/*
 * LoginDialog.java
 *
 * Created on September 8, 2008, 3:57 PM
 */

package canary;

import java.awt.Frame;
import java.util.prefs.Preferences;
import javax.swing.JOptionPane;
import org.jdesktop.application.Action;
import org.netbeans.saas.RestResponse;
import org.netbeans.saas.twitter.TwitterWhatAreYouDoingServiceAuthenticator;

/**
 *
 * @author  hulles
 */
public class LoginDialog extends javax.swing.JDialog {
    private final Preferences pref;
    private String userID;
    private String password;
    private final TwitterUtils twitter;
    private Frame parentFrame;
    private boolean loggedIn = false;

    /** Creates new form LoginDialog */
    public LoginDialog(Frame parent) {
        super(parent,true);
        pref = Preferences.userNodeForPackage(TwitterWhatAreYouDoingServiceAuthenticator.class);
        this.parentFrame = parent;
        initComponents();
        getRootPane().setDefaultButton(okButton);
        twitter = new TwitterUtils();
        userID = pref.get("userID", "");
        password = pref.get("password", "");
        userIDField.setText(userID);
        passwordField.setText(password);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        userIDField = new javax.swing.JTextField();
        passwordField = new javax.swing.JPasswordField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        okButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(canary.CanaryApp.class).getContext().getResourceMap(LoginDialog.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setAlwaysOnTop(true);

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(canary.CanaryApp.class).getContext().getActionMap(LoginDialog.class, this);
        okButton.setAction(actionMap.get("okAction")); // NOI18N
        okButton.setText(resourceMap.getString("okButton.text")); // NOI18N

        cancelButton.setAction(actionMap.get("cancelAction")); // NOI18N
        cancelButton.setText(resourceMap.getString("cancelButton.text")); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addGap(23, 23, 23)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(userIDField)
                    .addComponent(passwordField, javax.swing.GroupLayout.DEFAULT_SIZE, 293, Short.MAX_VALUE))
                .addContainerGap(12, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(272, Short.MAX_VALUE)
                .addComponent(cancelButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(okButton)
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cancelButton, okButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(userIDField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 74, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(okButton)
                    .addComponent(cancelButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    @Action
    public void cancelAction() {
        loggedIn = false;
        setVisible(false);
    }

    public boolean successfulLogin() {
        return loggedIn;
    }
    
    @Action
    public void okAction() {
        String saveUserID;
        String savePassword;
        RestResponse result;
        String resultString;
        
        setVisible(false);
        loggedIn = false;
        
        // TODO: returns clear text, might want to change that
        userID = userIDField.getText();
        password = new String(passwordField.getPassword());
        saveUserID = pref.get("userID", "");
        savePassword = pref.get("password", "");
        pref.put("userID", userID);
        pref.put("password", password);
        result = twitter.verifyLogin();
        if (result == null) {
            JOptionPane.showMessageDialog(LoginDialog.this, "Unable to verify Twitter login at this time.", "Log In Error", JOptionPane.ERROR_MESSAGE);
            pref.put("userID", saveUserID);
            pref.put("password", savePassword);
            userID = saveUserID;
            password = savePassword;
        } else {
            System.out.println("LoginDialog: result = " + result.getDataAsString());
            resultString = TwitterUtils.requestResponse(result);
            if (resultString != null) {
                JOptionPane.showMessageDialog(LoginDialog.this, resultString, "Log In Error", JOptionPane.ERROR_MESSAGE);
                pref.put("userID", saveUserID);
                pref.put("password", savePassword);
                userID = saveUserID;
                password = savePassword;
            } else { 
                // it worked, leave prefs as is
                JOptionPane.showMessageDialog(LoginDialog.this, "Login for " + userID + " successful.", "Logged In To Twitter", JOptionPane.INFORMATION_MESSAGE);
                loggedIn = true;
            }
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JButton okButton;
    private javax.swing.JPasswordField passwordField;
    private javax.swing.JTextField userIDField;
    // End of variables declaration//GEN-END:variables

}
